using Domain.Examin;
using Domain.Production_Modules;
using Domain.User;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.ApprovalProcess;
using Microsoft.EntityFrameworkCore;
using ReturnValue;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MES.Server.API.Application.Handler.ApprovalProcess
{
    public class ApprovalPurchaseOrderHandler : IRequestHandler<ApprovalPurchaseOrderCommand, ApiResult<bool>>
    {
        private readonly IRepository<PurchaseOrderModel> purchaseOrderRepo;
        private readonly IRepository<ApprovalTaskHistModel> approvalHistoryRepo;
        private readonly IRepository<ApprovalNodeModel> approvalNodeRepo;
        private readonly IRepository<approvalProcessInstanceModel> processInstanceRepo;
        private readonly IRepository<AccountRoleModel> accountRoleRepo;

        public ApprovalPurchaseOrderHandler(
            IRepository<PurchaseOrderModel> purchaseOrderRepo,
            IRepository<ApprovalTaskHistModel> approvalHistoryRepo,
            IRepository<ApprovalNodeModel> approvalNodeRepo,
            IRepository<approvalProcessInstanceModel> processInstanceRepo,
            IRepository<AccountRoleModel> accountRoleRepo)
        {
            this.purchaseOrderRepo = purchaseOrderRepo;
            this.approvalHistoryRepo = approvalHistoryRepo;
            this.approvalNodeRepo = approvalNodeRepo;
            this.processInstanceRepo = processInstanceRepo;
            this.accountRoleRepo = accountRoleRepo;
        }

        public async Task<ApiResult<bool>> Handle(ApprovalPurchaseOrderCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<bool>();

            try
            {
                // 获取采购单信息
                var purchaseOrder = await purchaseOrderRepo.GetValue(request.PurchaseOrderId);

                if (purchaseOrder == null)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "采购单不存在";
                    result.Data = false;
                    return result;
                }
                if (purchaseOrder.Status ==2)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "该流程已完成审批结束";
                    result.Data = false;
                    return result;
                }
               
                // 检查采购单是否处于待审核状态
                if (purchaseOrder.Status != 0 && purchaseOrder.Status!=1)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "该采购单不处于待审核状态";
                    result.Data = false;
                    return result;
                }
                
                // 获取采购单审批流程实例
                var processInstance = await processInstanceRepo
                    .GetAll()
                    .Where(p => p.productionOrder == request.PurchaseOrderId && 
                           !p.IsDel)
                    .FirstOrDefaultAsync();
                
                if (processInstance == null)
                {
                    // 如果不存在流程实例，则创建一个新的（假设是第一次审批）
                    processInstance = new approvalProcessInstanceModel
                    {
                        Id = DateTime.Now.Ticks,
                        productionOrder = request.PurchaseOrderId,
                        processId = 1, // 采购审批流程ID，假设为1
                        currentNodeId = 1, // 初始节点为1（人事审批）
                        initiator = request.CurrentUserId,
                        status = 1, // 正在运行
                        starttiome = DateTime.Now
                    };
                    await processInstanceRepo.AddAsync(processInstance);
                }

                // 获取当前审批节点
                var currentNode = await approvalNodeRepo.GetValue(processInstance.currentNodeId);
                if (currentNode == null)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = "未找到当前审批节点";
                    result.Data = false;
                    return result;
                }
                
                // 检查当前用户是否有权限审批当前节点
                bool hasPermission = false;
                
                // 根据节点名称和用户角色判断权限
                switch (currentNode.nodeName)
                {
                    case "人事审批":
                        hasPermission = request.CurrentUserRole == "HR" || request.CurrentUserRole == "人事";
                        break;
                    case "财务审批":
                        hasPermission = request.CurrentUserRole == "Finance" || request.CurrentUserRole == "财务";
                        break;
                    case "董事长审批":
                        hasPermission = request.CurrentUserRole == "CEO" || request.CurrentUserRole == "董事长";
                        break;
                    default:
                        hasPermission = false;
                        break;
                }
                
                if (!hasPermission)
                {
                    result.Code = StatusCode.Fail;
                    result.Message = $"您没有权限审批当前节点【{currentNode.nodeName}】";
                    result.Data = false;
                    return result;
                }
                
                // 如果驳回，直接更新状态并结束审批
                if (!request.IsApproved)
                {
                    purchaseOrder.Status = 3; // 已驳回
                    await purchaseOrderRepo.UpdateAsync(purchaseOrder);
                    
                    // 更新流程实例状态为已终止
                    processInstance.status = 3; // 已终止
                    processInstance.endtime = DateTime.Now;
                    await processInstanceRepo.UpdateAsync(processInstance);
                    
                    // 记录审批历史
                    var rejectHistory = new ApprovalTaskHistModel
                    {
                        Id = DateTime.Now.Ticks,
                        errandInstanceid = processInstance.Id,
                        nodeId = currentNode.Id,
                        assigneeId = request.CurrentUserId,
                        taskstatus = 1, // 已审批
                        createtime = DateTime.Now,
                        approver = request.CurrentUserId,
                        action = 2, // 2：拒绝
                        comment = request.ApprovalComment,
                        handletime = DateTime.Now
                    };
                    await approvalHistoryRepo.AddAsync(rejectHistory);
                    
                    result.Code = StatusCode.Success;
                    result.Message = "采购单已驳回";
                    result.Data = true;
                    return result;
                }
                
                // 如果通过审批，更新流程状态并继续流程
                // 判断是否存在下一个节点
                if (currentNode.nextnodeId.HasValue && currentNode.nextnodeId.Value > 0)
                {
                    // 存在下一节点，流程继续
                    processInstance.currentNodeId = currentNode.nextnodeId.Value;
                    processInstance.status = 1; // 进行中状态
                    await processInstanceRepo.UpdateAsync(processInstance);
                    
                    // 当流程实例当前节点ID大于1时，将采购单状态改为进行中，否则保持待审批状态
                    if (processInstance.currentNodeId > 1)
                    {
                        purchaseOrder.Status = 1; // 进行中
                    }
                    else
                    {
                        purchaseOrder.Status = 0; // 待审批
                    }
                    await purchaseOrderRepo.UpdateAsync(purchaseOrder);
                    
                    // 获取下一个节点信息，用于消息提示
                    var nextNode = await approvalNodeRepo.GetValue(currentNode.nextnodeId.Value);
                    string nextNodeName = nextNode != null ? nextNode.nodeName : "下一审批环节";
                    
                    // 设置成功消息，包含下一审批环节
                    result.Message = $"已审批通过，流程已转到{nextNodeName}";
                }
                else
                {
                    // 不存在下一节点，即董事长已审批通过，流程结束
                    processInstance.currentNodeId = 0; // 0表示流程结束
                    processInstance.status = 2; // 已完成，董事长审批通过后状态为2
                    processInstance.endtime = DateTime.Now;
                    await processInstanceRepo.UpdateAsync(processInstance);
                    
                    // 采购单状态改为进行中
                    purchaseOrder.Status = 2; // 已完成
                    await purchaseOrderRepo.UpdateAsync(purchaseOrder);
                    
                    // 设置成功消息
                    result.Message = "采购单审批流程已全部完成";
                }
                
                // 记录审批历史 
                var approvalHistory = new ApprovalTaskHistModel
                {
                    Id = DateTime.Now.Ticks,
                    errandInstanceid = processInstance.Id,
                    nodeId = currentNode.Id,
                    assigneeId = request.CurrentUserId,
                    taskstatus = 1, // 已审批
                    createtime = DateTime.Now,
                    approver = request.CurrentUserId,
                    action = 1, // 1：通过
                    comment = request.ApprovalComment,
                    handletime = DateTime.Now
                };
                await approvalHistoryRepo.AddAsync(approvalHistory);

                result.Code = StatusCode.Success;
                result.Message = request.IsApproved ? "采购单审批通过" : "采购单已驳回";
                result.Data = true;
                return result;
            }
            catch (Exception ex)
            {
                result.Code = StatusCode.Fail;
                result.Message = $"审批过程中发生错误：{ex.Message}";
                result.Data = false;
                return result;
            }
        }
    }
}
